

const app = getApp()
const request = require('../../utils/request');

Page({
	data: {
		userInfo: {},
		hasUserInfo: true,
		canIUse: wx.canIUse('button.open-type.getUserInfo'),
		userHeaderUrl: '',	//用户头像
        userName: ''	//用户昵称
	},
	onLoad: function () {
		let that = this;
		console.log(that.data.userInfo)
		if(wx.getStorageSync('sessionId')){
			wx.checkSession({
				success: function(){
					//session_key 未过期，并且在本生命周期一直有效,直接获取信息
					console.log('session_key未过期')
					if (app.globalData.userInfo) {
						that.setData({
							userInfo: app.globalData.userInfo,
							hasUserInfo: true
						})
					} else if (that.data.userInfo){
						// 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
						// 所以此处加入 callback 以防止这种情况
						app.userInfoReadyCallback = res => {
							that.setData({
								userInfo: res.userInfo,
								hasUserInfo: true
							})
						}
					} else {
						// 在没有 open-type=getUserInfo 版本的兼容处理
						wx.getUserInfo({
							success: res => {
								app.globalData.userInfo = res.userInfo
								that.setData({
									userInfo: res.userInfo,
									hasUserInfo: true
								}),
								wx.setStorageSync('userHeaderUrl',res.userInfo.avatarUrl)
							}
						})

						console.log(that.data.userInfo)
					}
				},
				fail: function(){
					// session_key 已经失效，需要重新执行登录流程
					console.log('session_key已经过期')
					try {
						wx.removeStorageSync('sessionId')
					  } catch (e) {
						// Do something when catch error
					}
					that.setData({
						hasUserInfo: false,
						canIUse: wx.canIUse('button.open-type.getUserInfo')
					})
					wx.navigateTo({
						url: 'myLogin/myLogin'
					})
				  //request.myLogin(); //重新登录
				}
			})
			
		}else{
			that.setData({
				hasUserInfo: false,
				canIUse: wx.canIUse('button.open-type.getUserInfo')
			})
			wx.navigateTo({
				url: 'myLogin/myLogin'
			})
		}

		
	},
	onShow:	function(){
		//this.onLoad()
		let that = this;
		wx.getStorage({
            key: 'user',
            success: function(res){
                console.log(res)
                that.setData({
                    userHeaderUrl: res.data.userHeaderUrl,
                    userName: res.data.userName,
                })
            }
        })
	}
})